package com.asl.api.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.asl.api.service.TrackingProxyService;
import com.asl.website.core.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class TrackingProxyServiceImpl implements TrackingProxyService {

    @Value("${asl.tracking.url}")
    private String TARGET_URL;

    @Value("${asl.encryption.key}")
    private String DES_KEY;

    @Autowired
    private RestTemplate restTemplate;

    public Object getTrackingStatus(String hblNo) {
        try {
            // 参数清洗：去除首尾空格和引号
            String cleanHblNo = hblNo.trim().replaceAll("^\"|\"$", "");
//            System.out.println("[清洗后参数]: " + cleanHblNo);

            // 构建 JSON
            JSONObject param = new JSONObject();
            param.put("hbl_no", cleanHblNo);
            String plainJson = param.toJSONString();
//            System.out.println("[加密前明文]: " + plainJson);

            // DES 加密
            byte[] encrypted = desEncrypt(plainJson, DES_KEY);
            String base64Data = Base64.getEncoder().encodeToString(encrypted);
//            System.out.println("[Base64 编码]: " + base64Data);

            // 构建表单请求体
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("data", base64Data); // 参数放入data字段

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add("x-companyid", "vlpasl");
            headers.add("x-type", "gettrack");

            // 打印请求信息
//            System.out.println("===== 请求头信息 =====");
            headers.forEach((key, values) -> System.out.println(key + ": " + values));
//            System.out.println("===== 请求体内容 =====");
//            System.out.println("data: " + base64Data); // RestTemplate会自动进行URL编码
//            System.out.println("=====================");

            // 发送请求
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(TARGET_URL, request, String.class);
            String responseResult = response.getBody();
            Object parse = JSON.parse(responseResult);
//            System.out.println("[响应结果]: " + parse);
            return parse;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail("请求失败: " + e.getMessage());
        }
    }

    private byte[] desEncrypt(String data, String key) throws Exception {
        if (key.getBytes(StandardCharsets.UTF_8).length != 8) {
            throw new IllegalArgumentException("DES 密钥必须为 8 字节");
        }

        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
    }
}